package com.yc.swing.dao;

import java.sql.SQLException;

import com.ly.demo.taach.jdbc.impl.DBHelper;
import com.ly.demo.taach.jdbc.impl.DeptDao;

public class DeptDaoSub extends DeptDao {

	@Override
	public int insert(String dname, String loc) throws SQLException {
		// 事务实现自动生成编号
		DBHelper dbh = new DBHelper();
		try {
			String sql1 = "select max(deptno) + 1 from dept";
			String sql2 = "insert into dept values(?,?,?)";
			Object maxDeptno = dbh.selectValue(sql1);
			dbh.update(sql2, maxDeptno, dname, loc);
			// 正常业务提交
			dbh.commit();
		} catch (SQLException e) {
			// 异常情况下回滚
			dbh.rollback();
			// 抛出异常
			throw e;
		} finally {
			dbh.close();
		}

		return super.insert(dname, loc);
	}

	@Override
	public void update(int deptno, String dname, String loc) throws SQLException {
		try (DBHelper dbh = new DBHelper()) {
			dbh.update("update dept set dname=?,loc=? where deptno=?", dname, loc, deptno);
		}
	}

	@Override
	public void deleteByDeptno(int deptno) throws SQLException {
		try (DBHelper dbh = new DBHelper()) {
			String sql = "select count(*) from emp where deptno=?";
			Object cnt = dbh.selectValue(sql, deptno);
			Integer c = Integer.parseInt(cnt + "");
			if (c > 0) {
				throw new SQLException("该部门下还有员工股,不能删除", sql, -99);
			}
			dbh.update("delete from dept where deptno=?", deptno);
		}
	}

}
